import http from 'wechat-http'

http.baseURL = "https://live-api.itheima.net"

// 响应拦截器
http.intercept.response = async ({ data, statusCode, config }) => {
  // console.log(res);

  if (statusCode === 401) {
    if (config.url.includes('/refreshToken')) {
      // 当刷新 token 接口中的 refreshToken 失效时
      // 提示用户
      wx.utils.toast('登录超时，请重新登录')
      const pageStack = getCurrentPages()
      const currentPage = pageStack[pageStack.length - 1]
      // 退出登录，跳转到登录页，重新登录
      wx.redirectTo({ url: '/pages/login/index?returnUrl=/' + currentPage.route })
      return
    }
    // 刷新 token
    const res = await http({
      url: '/refreshToken',
      method: 'post',
      header: {
        Authorization: getApp().refreshToken
      }
    })
    if (res.code !== 10000) return wx.utils.toast()
    // console.log(res);
    // 存储 token 和 refresh_token
    getApp().setToken(res.data.token, res.data.refreshToken)

    // console.log(8, config);
    return http({
      ...config,
      header: {
        Authorization: getApp().token
      }
    })
  }
  // 解套
  return data
}

// 请求拦截器
http.intercept.request = (params) => {
  // params 请求相关的信息
  console.log(params);
  const token = getApp().token
  params.header = params.header || {}
  // token 存在，并且，调用的接口不是刷新 token 的接口时，再给接口添加 Authorization: token
  if (token && !params.url.includes('/refreshToken')) {
    params.header.Authorization = token
  }
  return params
}

wx.http = http
